package fr.mma.livraison;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;

import fr.mma.livraison.dao.AdminDao;
import fr.mma.livraison.model.dto.reponse.ReponseDTO;
import fr.mma.livraison.model.dto.reponse.ReponseKO;
import fr.mma.livraison.model.dto.reponse.ReponseOK;
import fr.mma.livraison.model.persistence.Admin;

@SuppressWarnings("serial")
public class AdminServlet extends HttpServlet {
	final private AdminDao dao = new AdminDao();

	public class AdminResponse {
		private String loginUrl;
		private String logoutUrl;
		private String name;

		public String getLoginUrl() {
			return loginUrl;
		}

		public void setLoginUrl(String loginUrl) {
			this.loginUrl = loginUrl;
		}

		public String getLogoutUrl() {
			return logoutUrl;
		}

		public void setLogoutUrl(String logoutUrl) {
			this.logoutUrl = logoutUrl;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}

	public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
		final Gson gson = new Gson();
		if (dao.getAll().isEmpty()) {
			final Admin admin = new Admin();
			admin.setId(1);
			admin.setName("mkl.lecoq@gmail.com");
			dao.save(admin);
		}

		ReponseDTO reponseDto;
		UserService userService = UserServiceFactory.getUserService();
		AdminResponse adminResponseDto = new AdminResponse();
		if (userService.isUserLoggedIn()) {
			adminResponseDto.setLogoutUrl(userService.createLogoutURL(req.getParameter("url")));
			adminResponseDto.setName(userService.getCurrentUser().getNickname());
		} else {
			adminResponseDto.setLoginUrl(userService.createLoginURL(req.getParameter("url")));
		}

		if (req.getUserPrincipal() != null && dao.isAdmin(req.getUserPrincipal().getName())) {
			reponseDto = new ReponseOK(adminResponseDto);
		} else {
			reponseDto = new ReponseKO("Pas admin", adminResponseDto);
		}
		resp.getWriter().println(gson.toJson(reponseDto));
	}
}
